//
//  LLNetworkTools.swift
//  WeiBoShiBing
//
//  Created by Bingo on 15/10/28.
//  Copyright © 2015年 Bingo. All rights reserved.
//
import UIKit
import AFNetworking
//网络下载数据工具类
//MAKR: -枚举。可以定义属性，方法
enum LLNetworkError:Int {
    
    case emptyToken = -1
    case emptyUid = -2
    var errorDescription:String{
        switch self{
        case.emptyToken: return "token为空"
        case.emptyUid: return "uid为空"
        }
        
    }
    func error()->NSError{
        return NSError(domain: "cn.itcast.error.net", code: rawValue, userInfo: ["errorDescription":errorDescription])
    }
}
class LLNetworkTools: NSObject {
    
    // 属性
    private var afnManager: AFHTTPSessionManager
    
    // 创建单例
    static let sharedInstance: LLNetworkTools = LLNetworkTools()
    
    override init() {
        let urlString = "https://api.weibo.com/"
        afnManager = AFHTTPSessionManager(baseURL: NSURL(string: urlString))
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }
    
    // 创建单例
    //    static let sharedInstance: LLNetworkTools = {
    //        let urlString = "https://api.weibo.com/"
    //
    //        let tool = LLNetworkTools(baseURL: NSURL(string: urlString))
    ////        Set
    //        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
    //
    //        return tool
    //    }()
    
    // MARK: - OAtuh授权
    /// 申请应用时分配的AppKey
    private let client_id = "3120024081"
    
    /// 申请应用时分配的AppSecret
    private let client_secret = "5b5840716115c7633f27f017a9ee2822"
    
    /// 请求的类型，填写authorization_code
    private let grant_type = "authorization_code"
    
    /// 回调地址
    let redierct_uri = "http://www.baidu.com"
    
    // OAtuhURL地址
    func oauthURL() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redierct_uri)"
        return NSURL(string: urlString)!
    }
    
    // 使用闭包回调
    // MARK: - 加载AccessToken
    /// 加载AccessToken
    func loadAccessToken(code: String, finshed: NetworkFinishedCallback) {
        // url
        let urlString = "oauth2/access_token"
        
        // NSObject
        // AnyObject, 任何 class
        // 参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redierct_uri
        ]
        
        // 测试返回结果类型
        //        responseSerializer = AFHTTPResponseSerializer()
        // result: 请求结果
        afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            //            let data = String(data: result as! NSData, encoding: NSUTF8StringEncoding)
            //            print("data: \(data)")
            
            finshed(result: result as? [String: AnyObject], error: nil)
            }) { (_, error: NSError) -> Void in
                finshed(result: nil, error: error)
        }
    }
    
    // MARK: - 获取用户信息
    func loadUserInfo(finshed: NetworkFinishedCallback) {
        guard var parameters = tokenDict() else{
            print("没有accessToken")
            let error = LLNetworkError.emptyToken.error()
            finshed(result: nil, error: error)
            return
        }
        //判断uid
        if LLUserAccount.loadAccount()?.uid == nil {
            let error = LLNetworkError.emptyUid.error()
            print("没有uid")
            
            finshed(result: nil, error: error)
            return
        }
        
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        parameters["uid"] = LLUserAccount.loadAccount()!.uid!
        // 参数
        //        let parameters = [
        //            "access_token": LLUserAccount.loadAccount()!.access_token!,
        //            "uid": LLUserAccount.loadAccount()!.uid!
        //        ]
        
        requestGET(urlString, parameters: parameters, finshed: finshed)
        
        //        // 发送请求
        //        afnManager.GET(urlString, parameters: parameters, success: { (_, result) -> Void in
        //            finshed(result: result as? [String: AnyObject], error: nil)
        //            }) { (_, error) -> Void in
        //                finshed(result: nil, error: error)
        //        }
    }
    /// 判断access token是否有值,没有值返回nil,如果有值生成一个字典
    func tokenDict()->[String:AnyObject]?{
        if LLUserAccount.loadAccount()?.access_token == nil{
            return nil
        }
        
        return ["access_token":LLUserAccount.loadAccount()!.access_token!]
    }
    
    //获取微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: NetworkFinishedCallback) {
        guard var parameters = tokenDict() else {
            // 能到这里来说明token没有值
            
            // 告诉调用者
            finished(result: nil, error: LLNetworkError.emptyToken.error())
            return
        }
        
        // 添加参数 since_id和max_id
        // 判断是否有传since_id,max_id
        if since_id > 0 {
            parameters["since_id"] = since_id
        } else if max_id > 0 {
            parameters["max_id"] = max_id - 1
        }
        
        // access token 有值
        let urlString = "2/statuses/home_timeline.json"
        // 网络不给力,加载本地数据
        if true {
            requestGET(urlString, parameters: parameters, finshed: finished)
        } else {
            loadLocalStatus(finished)
        }
    }
    
    //    func loadStatus(finished:NetworkFinishedCallback){
    //        guard let parameters = tokenDict()else {
    //            finished(result: nil, error: LLNetworkError.emptyToken.error())
    //            return
    //        }
    //        let urlString = "2/statuses/home_timeline.json"
    //        requestGET(urlString, parameters: parameters, finshed: finished)
    //        //加载本地数据
    ////        loadStatus(finished)
    //    }
    //加载本地数据
    private func loadLocalStatus(finished:NetworkFinishedCallback){
        let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")
        let data = NSData(contentsOfFile: path!)
        //MARK: - 异常处理   DO CATCH
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
            finished(result: json as![String:AnyObject], error: nil)
        }catch{
            print("出异常了")
            
        }
        
        
    }
    func sendStatus(image:UIImage?,status:String,finished:NetworkFinishedCallback){
        
        guard var parameters = tokenDict() else{
            
            finished(result: nil, error: LLNetworkError.emptyToken.error())
            return
        }
        
        parameters["status"] = status
        //发送微博请求的url
        
        if let im = image {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            afnManager.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                let data = UIImagePNGRepresentation(im)!
                
                formData.appendPartWithFileData(data, name: "pic", fileName: "sb", mimeType: "image/png")
                }, success: { (_, result) -> Void in
                    
                finished(result: result as! [String : AnyObject], error: nil)
                    
                }, failure: { (_, error) -> Void in
                    finished(result: nil, error: error)
            })
        }else{
        
            let urlString = "2/statuses/update.json"
        afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            
            finished(result: result as! [String : AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
        
      }
    }
    // 类型别名 = typedefined
    typealias NetworkFinishedCallback = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    // MARK: - 封装AFN.GET
    func requestGET(URLString: String, parameters: AnyObject?, finshed: NetworkFinishedCallback) {
        
        afnManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in
            finshed(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                finshed(result: nil, error: error)
        }
    }
    
    
}


// MARK: - 异常代码
//import UIKit
//import AFNetworking
//
//class LLNetworkTools: NSObject {
//
//
//    private var afnManager:AFHTTPSessionManager
//
//    static let sharedInstance:LLNetworkTools = LLNetworkTools()
//
////    {
////        let urlString = "https://api.weibo.com/"
//
////        let tool = LLNetworkTools(baseURL: NSURL(string: urlString))
////        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
////
////       return tool
////    }()
//    override init() {
//        let urlString = "https://api.weibo.com/"
//        afnManager = AFHTTPSessionManager(baseURL: NSURL(string: urlString))
//        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//    }
//
//    private let client_id = "3120024081"
//    private let client_secret = "5b5840716115c7633f27f017a9ee2822"
//
//    private let grant_type = "authorization_code"
//
//    let redierct_uri = "http://www.baidu.com"
//
//    func oauthURL() ->NSURL{
//        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redierct_uri)"
//        print("\(urlString)")
//        return NSURL(string: urlString)!
//    }
//
//    func loadAccessToken(code:String,finshed:(result:[String:AnyObject]?,error:NSError?)->()){
//        let urlString = "oauth2/access_token"
//
//        let parameters = [
//            "client_id":client_id,
//            "client_secret":client_secret,
//            "grant_type":grant_type,
//            "code":code,
//            "redirect_uri":redierct_uri
//        ]
//
//       afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//
//            finshed(result:result as?[String:AnyObject], error:nil)
//            }) { (_,error:NSError) -> Void in
//
//                finshed(result: nil, error:error)
//        }
//    }
//    func loadUserInfo(finshed:NetworkFinishedCallback){
//        if LLUserAccount.loadAccount()?.access_token == nil{
//            print("没有accessToken")
//            return
//        }
//
//        if LLUserAccount.loadAccount()?.uid == nil{
//            print("没有uid")
//            return
//        }
//
//        let urlString = "https://api.weibo.com/2/users/show.json"
//
//        let parameters = [
//            "access_token":LLUserAccount.loadAccount()!.access_token!,
//            "uid":LLUserAccount.loadAccount()!.uid!
//        ]
//
//        requestGET(urlString, parameters: parameters, finshed: finshed)
//    }
//
//    typealias NetworkFinishedCallback = (result:[String:AnyObject]?,error:NSError) ->()
//
//    func requestGET(URLString:String,parameters:AnyObject?,finshed:NetworkFinishedCallback){
//
//        afnManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in
//
//            finshed(result: result as? [String:AnyObject] , error: nil)
//            }) { (_, error) -> Void in
//            finshed(result: nil, error: error)
//        }
//    
//    }
//}
